import React, { useMemo, useEffect, useState } from "react";
import { Form, Radio, Input, Button, Icon, Col, message, Select } from "antd";
import TemplateItem from "./components/TemplateItem";
import styles from "./AddTemplate.less";
import {
  saveMessageTemplate,
  getTemplateDetail,
  commitMessageTemplate,
  getSmsSign
} from "../../services/messageTemplateApi";
import { getQueryVariable } from '../../../../utils/utils';

const { TextArea } = Input;

function AddTemplate(props) {
  const {
    form,
    // location: { search },
    history
  } = props;
  // const searchParams = new URLSearchParams(search.substring(1));
  // const templateId = searchParams.get("templateId");
  // const id = searchParams.get("id");
  const templateId = getQueryVariable("templateId");
  const id = getQueryVariable("id");
  const {
    getFieldDecorator,
    getFieldValue,
    setFieldsValue,
    getFieldsValue,
    validateFields
  } = form;
  const [contentArr, setContentArr] = useState([]); // 维护一个数组用以给下层TemplateItem组件回显数据
  const [signNames, setsignNames] = useState([]); // 短信签名
  const validateArr = getFieldsValue() ? getFieldsValue().val : [{}]; // 校验用数组
  const selectItem = getFieldsValue()
    ? getFieldsValue().val && getFieldsValue().val.filter(item => item.value)
    : []; // 下拉框列表渲染数组
  const contentSelect = getFieldsValue() ? getFieldsValue().content : "";
  const type = getFieldValue("type");
  const labelCol = { span: 3 };

  const createId = () => {
    // 私有变量
    let selfId = 0;
    return Object.create(null, {
      get: {
        value: () => {
          selfId += 1;
          return selfId;
        }
      }
    });
  };
  // 维护一个唯一id
  const varId = useMemo(() => createId(), []);

  // 编辑时数据回显
  useEffect(() => {
    if (templateId) {
      getTemplateDetail({ templateId }).then(res => {
        if (res.success) {
          const { datas } = res;
          // 将json字符串转换回数组，用于渲染定义变量字段
          const fields = [];
          const obj = JSON.parse(datas.fields);
          Object.keys(obj).forEach(key => {
            fields.push({
              key,
              value: obj[key]
            });
          });
          // antd3，需要根据keys字段进行渲染
          const keys = [0];
          for (let i = 0; i < fields.length - 1; i += 1) {
            keys.push(varId.get());
          }
          // 将content拆分成数组以便后续渲染以及回显
          const content = datas.content
            .split("#")
            .filter(item => item)
            .map(item => {
              if (item === "\n") {
                return {
                  type: "enter",
                  value: item
                };
              }
              if (/^{[\s\S]+}$/.test(item)) {
                return {
                  type: "select",
                  value: item.slice(1, -1)
                };
              }
              return {
                type: "input",
                value: item
              };
            });
          setContentArr(content);
          setFieldsValue(
            {
              content: datas.content,
              displayContent: datas.displayContent,
              description: datas.description,
              keys,
              name: datas.name,
              smsSignId: datas.smsSignId,
              title: datas.title,
              type: datas.type
            },
            () => {
              // 根据keys渲染出对应节点后才能进行剩下的数据回显
              setFieldsValue({
                val: fields
              });
            }
          );
        }
      });
    }
    getSmsSign().then(({ errCode, datas = [] }) => {
      if (errCode === 0) {
        setsignNames(datas);
      }
    });
    // 获取短信签名列表
  }, [templateId]);

  // 提交/保存
  const onSubmit = (e, submitApi, msg) => {
    e.preventDefault();
    // 校验是否存在未定义变量
    const isSelect = contentSelect
      .split("#")
      .filter(i => /^{[\s\S]+}$/.test(i));
    const notUndefined = isSelect.length
      ? isSelect.find(j => {
          if (selectItem.find(k => `{${k.value}}` === j)) {
            return true;
          }
          return false;
        })
      : true;
    form.validateFields((err, values) => {
      if (!err) {
        if (notUndefined) {
          // 将数组转换成json字符串再传递给后台
          const fields = Object.create(null, {});
          values.val.forEach(element => {
            fields[element.key] = element.value;
          });
          const params = {
            id,
            templateId,
            content: values.content,
            displayContent: values.displayContent,
            description: values.description,
            fields: JSON.stringify(fields),
            name: values.name,
            smsSignId: values.smsSignId,
            title: values.title,
            type: values.type
          };
          submitApi(params).then(res => {
            if (res.success) {
              message.success(msg);
              history.go(-1);
            } else {
              message.error(res.errMsg);
            }
          });
        } else {
          message.error(
            "模板内容存在未定义变量，可能是由于您修改过变量名称，请移除未定义变量再提交"
          );
        }
      }
    });
  };

  // 动态增减表单的'定义变量'字段
  const renderVarItem = () => {
    const add = () => {
      // antd3官方文档 新建字段keys: Number[]，通过keys进行渲染
      const keys = form.getFieldValue("keys");
      const nextKeys = keys.concat(varId.get());
      form.setFieldsValue({
        keys: nextKeys
      });
    };
    const remove = k => {
      const keys = form.getFieldValue("keys");
      const value = form.getFieldValue(`val[${k}].value`);
      if (Number.isNaN(Number(value))) {
        const reg = new RegExp(`^{${value}}$`);
        const isUsed = contentSelect.split("#").find(item => reg.test(item));
        if (isUsed) {
          message.error("当前变量已被使用，删除前请先移除占用");
          return false;
        }
      }
      form.setFieldsValue(
        {
          keys: keys.filter(key => key !== k)
        },
        () => {
          // 触发下拉框刷新
          form.setFieldsValue(
            {
              [`val${k}`]: undefined
            },
            () => {
              // 触发校验
              validateFields(["val"], { force: true });
            }
          );
        }
      );
      return true;
    };

    // 初始渲染一项
    getFieldDecorator("keys", { initialValue: [0] });
    const keys = getFieldValue("keys");

    // antd3，双向校验是否重复命名
    const validatorOther = (index, e, method) => {
      form.setFieldsValue(
        {
          [`val[${index}].${method}`]: e.target.value
        },
        () => {
          keys.forEach((item, i) => {
            if (index !== i) {
              validateFields(
                [`val[${i}].${method}`],
                { force: true },
                () => {}
              );
            }
          });
        }
      );
    };

    return (
      <React.Fragment>
        {keys.map((key, index) => (
          <Form.Item
            labelCol={index === 0 ? labelCol : {}}
            wrapperCol={index !== 0 ? { offset: 3 } : {}}
            label={index === 0 && "定义变量"}
            key={key}
            required
          >
            <Form.Item
              style={{
                display: "inline-block",
                marginRight: 9,
                marginBottom: 0
              }}
            >
              {getFieldDecorator(`val[${key}].key`, {
                rules: [
                  {
                    validator: async (rule, value) => {
                      if (!value) throw new Error("请输入变量名称");
                      if (
                        validateArr
                          .filter(item => item)
                          .find((item, i) => item.key === value && i !== index)
                      )
                        throw new Error("变量名称重复");
                    }
                  }
                ]
              })(
                <Input
                  style={{ width: 116 }}
                  placeholder="请输入变量名称"
                  onChange={e => validatorOther(key, e, "key")}
                />
              )}
            </Form.Item>
            <Form.Item
              required
              style={{ display: "inline-block", marginBottom: 0 }}
            >
              {getFieldDecorator(`val[${key}].value`, {
                rules: [
                  {
                    validator: async (rule, value) => {
                      if (!value) throw new Error("请输入变量值");
                      if (
                        validateArr
                          .filter(item => item)
                          .find(
                            (item, i) => item.value === value && i !== index
                          )
                      )
                        throw new Error("变量值重复");
                      if (!/^(_|[A-Za-z])/.test(value))
                        throw new Error("变量值只能以英语或下划线开头");
                      if (!/^(_|[A-Za-z])([_|A-Za-z|\d|.]*)$/.test(value))
                        throw new Error("变量值只能由英语，下划线以及数字组成");
                    }
                  }
                ]
              })(
                <Input
                  onChange={e => validatorOther(key, e, "value")}
                  style={{ width: 241 }}
                  placeholder="请输入变量值"
                />
              )}
            </Form.Item>
            {keys.length > 1 && (
              <Icon
                type="close-circle"
                theme="filled"
                style={{ color: "red", marginLeft: 12 }}
                onClick={() => remove(key)}
              />
            )}
          </Form.Item>
        ))}
        <Col style={{ marginBottom: 16 }} offset={3}>
          <Button onClick={add} type="primary" style={{ width: 366 }}>
            +定义变量
          </Button>
        </Col>
      </React.Fragment>
    );
  };

  return (
    <div className={styles.root}>
      <Form labelAlign="left" colon={false}>
        <Form.Item labelCol={labelCol} label="模板类型">
          {getFieldDecorator("type", {
            rules: [{ required: true }],
            initialValue: 2
          })(
            <Radio.Group>
              {/* <Radio.Button value={1}>APP模板</Radio.Button> */}
              <Radio.Button value={2}>短信模板</Radio.Button>
            </Radio.Group>
          )}
        </Form.Item>
        <Form.Item
          labelCol={labelCol}
          wrapperCol={{ span: 8 }}
          label="模板名称"
        >
          {getFieldDecorator("name", {
            rules: [{ required: true, message: "请输入模板名称" }]
          })(<Input placeholder="请输入模板名称" style={{ width: 366 }} />)}
        </Form.Item>
        <Form.Item
          labelCol={labelCol}
          wrapperCol={{ span: 8 }}
          label="短信签名"
        >
          {getFieldDecorator("smsSignId", {
            rules: [{ required: true, message: "请选择短信签名" }]
          })(
            // <Input placeholder="请输入模板名称" style={{ width: 366 }} />
            <Select
              style={{ width: 366 }}
              allowClear
              placeholder="请选择短信签名"
            >
              {signNames.map(sign => (
                <Select.Option
                  value={sign.id}
                  key={sign.id}
                  disabled={sign.templateId}
                >
                  {sign.signName}
                </Select.Option>
              ))}
            </Select>
          )}
        </Form.Item>
        {renderVarItem()}
        {type === 1 && (
          <Form.Item labelCol={labelCol} label="模板内容">
            {getFieldDecorator("title", {
              rules: [{ required: true, message: "请输入模板标题" }]
            })(<Input placeholder="标题" style={{ width: 366 }} />)}
          </Form.Item>
        )}

        <TemplateItem
          form={form}
          contentArr={contentArr}
          selectItem={selectItem}
        />

        <Form.Item labelCol={labelCol} label="使用场景描述">
          {getFieldDecorator("description")(
            <TextArea
              maxLength={255}
              autoSize={{ minRows: 3 }}
              style={{ width: 800 }}
            />
          )}
        </Form.Item>
      </Form>

      <div className={styles.footer}>
        <Button
          type="primary"
          onClick={e => onSubmit(e, commitMessageTemplate, "提交成功")}
        >
          提交
        </Button>
        <Button
          onClick={e => onSubmit(e, saveMessageTemplate, "保存成功")}
          style={{ margin: "0 8px" }}
          type="primary"
        >
          保存
        </Button>
        <Button onClick={() => history.go(-1)}>取消</Button>
      </div>
    </div>
  );
}

export default Form.create()(AddTemplate);
